<?php 
namespace app\admin\controller;

use app\common\model\CheckworkLeave;
use app\common\model\CheckworkParam;
use app\common\model\CheckworkRecord;
use app\common\model\CompanyDepartment;
use app\common\model\CompanyStaff;
use app\common\model\CompanyStaffDepart;
use think\Exception;
use think\Db;
use app\common\controller\Wechat;
use app\common\model\CheckworkLeaveMsg;

class Checkwork extends Base
{
	/**
	 * 获取考勤参数
	 */
	public function getCheckWorkParam()
	{
		$param = CheckworkParam::get(1)->toArray();
		return $this->success($param);
	}
	
	/**
	 * 修改考勤参数
	 */
	public function editCheckWorkParam()
	{
		$data = $this->request->param('');
		try {
			$data['on_time'] = strtotime($data['on_time']);
			$data['off_time'] = strtotime($data['off_time']);
			CheckworkParam::get($data['id'])->save($data);
		} catch (Exception $e) {
			return $this->error($e->getMessage());
		}
		return $this->success('修改成功');
	}
	
	/**
	 * 考勤记录
	 */
	public function checkworkRecord()
	{
		//获取客户端传递的数据
		$data = $this->request->param('');
		/* $data = [
				'day' => 0,
				'state' => 2,
				'times' => '',
				'depart' => 0,
				'name' => '',
				'visit' => 1,
		]; */
		//初始化查询条件
		$where = [];
		if($data['day'] < 6) {
			$day = $this->setDay($data['day']);
			$where['create_time'] = ['between',[$day[0],$day[1]]];
		}
		if($data['state']) {
			$where['state'] = $data['state'];
		}
		//部门姓名查询
		if($data['name'] && $data['depart']) {
			$staff_ids = CompanyStaffDepart::where(['depart_id'=> $data['depart']])->column('staff_id');
			$where['staff_id'] = CompanyStaff::where(['id' =>['in',$staff_ids],'name' => $data['name']])->value('id');
		} elseif($data['name'] && !$data['depart']) {
			$where['staff_id'] = CompanyStaff::where(['name' => $data['name']])->value('id');
		} elseif ($data['depart'] && !$data['name']) {
			$staff_ids = CompanyStaffDepart::where(['depart_id'=> $data['depart']])->column('staff_id');
			$where['staff_id'] = ['in',$staff_ids];
		}
		//时间段查询
		if(is_array($data['times'])) {
			$times1 = strtotime($data['times'][0]);
			$times2 = strtotime($data['times'][1]);
			$where['create_time'] = ['between',[$times1,$times2]];
		}
		$list = CheckworkRecord::where($where)->order('id desc')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['name'] = CompanyStaff::get($rows['staff_id'])->name;
			$depart_id = CompanyStaffDepart::where(['staff_id' => $rows['staff_id']])->value('depart_id');
			$rows['depart'] = CompanyDepartment::get($depart_id)->depart_name;
		}
		//获取部门列表
		$depart_list = $data['visit'] ? [] : CompanyDepartment::where(['state' => 1])->field('id,depart_name')->select()->toArray();
		//重组数据结构
		$res = [
				'depart' => $depart_list,
				'record' => $list
		];
		return $this->success($res);
	}
	
	/**
	 * 设置查询时间
	 * @param unknown $day
	 * @return number[]
	 */
	private function setDay($day)
	{
		switch ($day) {
			case 0:
				//获取今日开始时间
				$start_time = mktime(0,0,0,date('m'),date('d'),date('Y'));
				//获取今日结束时间
				$end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
				break;
			case 1:
				//获取昨日开始时间
				$start_time = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
				//获取昨日结束时间
				$end_time = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
				break;
			case 2:
				$now_week = date('w');
				if($now_week == 0)$now_week = 7;
				//获取本周开始时间
				$start_time = strtotime(date('Y-m-d').'00:00:00') - ($now_week - 1)*24*60*60;
				//获取本周结束时间
				$end_time = strtotime(date('Y-m-d').'23:59:59') + (7 - $now_week)*24*60*60;
				break;
			case 3:
				//获取上周开始时间
				$start_time = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
				//获取上周结束时间
				$end_time = mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
				break;
			case 4:
				//获取本月开始时间
				$start_time = mktime(0,0,0,date('m'),1,date('Y'));
				//获取本月结束时间
				$end_time = mktime(23,59,59,date('m'),date('t'),date('Y'));
				break;
			case 5:
				//获取上个月的开始时间
				$start_time = strtotime('-1 month');
				//获取上个月的结束时间
				$end_time = strtotime(-date('d').'day');
				break;
		}
		return [$start_time,$end_time];
	}
	
	/**
	 * 统计月份每个员工的打卡记录
	 */
	public function monthSettlement()
	{
		//获取客户端传递的数据
		$month = $this->request->param('month');
		//获取客户端传递的本月应休息天数
		$rest_day = 5;//$this->request->param('rest_day');
		//获取员工列表
		$staffs = CompanyStaff::where(['leave_state' => 1,'state' => 1])->select()->toArray();
		//获取本月多少天
		$month_day = cal_days_in_month(CAL_GREGORIAN, $month, date('Y'));
		//获取本月开始时间
		$start_time = strtotime(date("Y-{$month}-1 00:00:00"));
		//获取本月结束时间
		$end_time = strtotime(date("Y-{$month}-{$month_day} 23:59:59"));
		//查询当月所有打卡记录
		$month_work = CheckworkRecord::where(['create_time' => ['between',[$start_time,$end_time]]])->select()->toArray();
		$arr = [];
		for ($i = 1;$i <= $month_day ;$i ++) {
			$arr[date("Y-m-{$i}")] = [];
			foreach ($month_work as $row) {
				if(strtotime(date("Y-m-{$i}")) == strtotime( $row['create_time'])) {
					$arr[date("Y-m-{$i}")][$row['staff_id']] = $row;
				}
			}	
		}
		$res = [];
		//数据重组
		foreach ($staffs as $rows) {
			$temp = [];
			for ($i = 1;$i <= $month_day ;$i ++) {
				$item_temp = $arr[date("Y-m-{$i}")];
				if(array_key_exists($rows['id'], $item_temp)) {
					$on_time = $item_temp[$rows['id']]['on_time'];
					$off_time = $item_temp[$rows['id']]['off_time'];
					$temp[] = [
							'on_time' => $on_time,
							'off_time' => $off_time,
					];
				} else {
					$temp[] = [
							'on_time' => '',
							'off_time' => '',
					];
				}
			}
			$res[] = [
					'name' => $rows['name'],
					'staff_id' => $rows['id'],
					'record' => $temp,
					'salary' => '未结算'
			];
		}
		return $this->success($res);
	}
	
	/**
	 * 员工请假记录
	 */
	public function checkworkLeave()
	{
		$data = $this->request->param('');
		$where = []; //初始化查询条件
		if($data['staff_name'] && !$data['staff_no']) {
			$staff_id = CompanyStaff::where(['name' => $data['staff_name']])->value('id');
			$where['staff_id'] = $staff_id;
		}elseif($data['staff_no'] && !$data['staff_name']) {
			$staff_id = CompanyStaffDepart::where(['no' => $data['staff_no']])->value('staff_id');
			$where['staff_id'] = $staff_id;
		}elseif($data['staff_no'] && $data['staff_name']){
			$staff_id1 = CompanyStaff::where(['name' => $data['staff_name']])->value('id');
			$staff_id = CompanyStaffDepart::where(['no' => $data['staff_no']])->value('staff_id');
			if($staff_id1 == $staff_id)$where['staff_id'] = $staff_id;
		}
		$list = CheckworkLeave::where($where)->order('state asc,id desc')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['no'] = CompanyStaffDepart::where(['staff_id' => $rows['staff_id']])->value('no');
			$rows['name'] = CompanyStaff::get($rows['staff_id'])->name;
		}
		return $this->success($list);
	}
	/**
	 * 请假审核操作
	 */
	public function updateLeaveState()
	{
		 $id = $this->request->param('id');
		 $state = $this->request->param('state');
		 Db::startTrans();
		 try {
		 	$leave = CheckworkLeave::get($id);
		 	if($leave->state)throw new Exception('状态错误');
		 	switch ($state) {
		 		case 1:
		 			$update = ['state' => 1];
		 			break;
		 		case 2:
		 			$update = ['state' => 2];
		 			break;
		 	}
		 	$update['update_time'] = time();
		 	$update['auditor'] = '微联管理员';
		 	$leave->save($update);
		 	//添加消息通知
		 	$msg = $state == 1 ? '同意' : '拒绝';
		 	$title = $state == 1 ? '请假申请通过通知' : '请假申请拒绝通知';
		 	$msg_info = [
		 			'staff_id' => $leave->staff_id,
		 			'leave_id' => $id,
		 			'auditor' => '微联管理员',
		 			'content' => "您在{$leave->create_time}提交的请假申请已被{$msg}",
		 			'create_time' => time(),
		 			'title' => $title,
		 			'state' => $state == 1 ? 1 : 0
		 	]; 
		 	CheckworkLeaveMsg::create($msg_info);
		 	Db::commit();
		 } catch (Exception $e) {
		 	Db::rollback();
		 	return $this->error($e->getMessage());
		 }
		 //微信公众号通知 
		 $openid = CompanyStaff::get($leave->staff_id)->openid;
		 $content = "您在{$leave->create_time}提交的请假申请已被{$msg}";
		 Wechat::toUserMsg($openid, $content);
		 return $this->success($state == 1 ? '同意成功' : '拒绝成功');
	}
}